<?php

namespace App\Console\Commands;

use App\Helpers\Utils;
use App\Models\Dorm;
use Illuminate\Console\Command;

class DormTypeAutoFix extends Command
{
    /**
     * The name and signature of the console command.
     *
     * @var string
     */
    protected $signature = 'dorm-type:auto_fix {--i|initial}';

    /**
     * The console command description.
     *
     * @var string
     */
    protected $description = 'auto fix dorm type according to rule in Utils get_dorm_type_auto_fix';

    /**
     * Create a new command instance.
     *
     * @return void
     */
    public function __construct()
    {
        parent::__construct();
    }

    /**
     * Execute the console command.
     *
     * @return mixed
     */
    public function handle()
    {
        $this->call('calc:work-years');
        if($this->option('initial')){
            Dorm::query()->where('floor',1)->whereIn('dorm_type_id',[2,9,10,11,12,13])->update(['dorm_type_id'=>9]);
            Dorm::query()->where('floor','>',1)->whereIn('dorm_type_id',[2,9,10,11,12,13])->update(['dorm_type_id'=>2]);
            $this->info('initial completed');
        }else{
            $rules = Utils::get_dorm_type_auto_fix();
            foreach ($rules as $rule) {
                $from_type = $rule['from_type_id'];
                $to_type = $rule['to_type_id'];
                $floor = $rule['floor_lower'];
                $work_years = $rule['work_years'];
                $this->warn("current rule: work years>=$work_years floor_lower>=$floor from_type_id=$from_type to_type_id=$to_type");

                $dorms = Dorm::with('staffs')->where('dorm_type_id', $from_type)->where('floor', '>=', $floor)->get();
                foreach ($dorms as $dorm) {
                    if($dorm->staffs->count()){
                        $max_year = $dorm->staffs->max('work_years');
                        $staff_ids = $dorm->staffs->reduce(function ($c,$i){
                            return $c.$i->id.';';
                        });
                        if ($max_year && $max_year>= $work_years) {
                            $dorm->dorm_type_id = $to_type;
                            $dorm->save();
                            $this->info("staff_ids=$staff_ids in dorm_id=$dorm->id  dorm_type_id changed from $dorm->dorm_type_id to $to_type");
                        }else{
                            $this->info("staff_ids=$staff_ids max work_year=$max_year smaller than $work_years");
                        }
                    }
                }

            }
        }

    }
}
